angular.module('avoidMistakes.services', [])

.factory('InitService', ['$q', '$rootScope', '$ionicPlatform', '$ionicHistory', '$timeout', '$cordovaToast',
	function($q, $rootScope, $ionicPlatform, $ionicHistory, $timeout, $cordovaToast) {
	    var defer = $q.defer();

		init();

		return defer.promise;

		function init () {
			$ionicPlatform.registerBackButtonAction(
				onHardwareBackButton,
				110
			);

			document.addEventListener('serialport.DataReceived', function (e) {
                $rootScope.$broadcast('serialport.DataReceived', e.serialPortData, e.serialPort);
            }, false);

			defer.resolve();
		}

		var _confirmExit = false;
		function onHardwareBackButton(e) {
			if ($ionicHistory.backView()) {
			 	$ionicHistory.goBack();
			} else {
				if (_confirmExit) {
					ionic.Platform.exitApp();
				} else {
					_confirmExit = true;
					$cordovaToast.showShortBottom('再按一次退出');
					$timeout(function () {
					 	_confirmExit = false;
					}, 2000);
				}
			}

			e.preventDefault();
			return false;
		} 
	}
]);
